package com.zj.study;

import java.util.*;

/*
A ,B,C,D,E
判断大家是否在一个朋友圈，第三个数为0表示是朋友，第三个数为1表示要输出判断关系。
 */
public class 根据信息进行朋友圈逐行判定copy {
    private static String[] persons = {"A", "B", "C", "D", "E"};

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("A E 0");
        list.add("A B 0");
        list.add("B E 1");
        list.add("B C 0");
        list.add("A D 1");
        list.add("C E 1");
        isOneFriendCirculer(list, 5);
    }

    //用并查集来判断是否师一个朋友圈
    public static void isOneFriendCirculer(List<String> parma, int len) {
        int[] parentRel = new int[len];
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < len; i++) {
            parentRel[i] = i;
            map.put(persons[i], i);
        }
        for (String str : parma) {
            String[] relation = str.split(" ");
            if (relation[2].trim().equals("0")) {
                union(map.get(relation[0]), map.get(relation[1]), parentRel);
            } else if (relation[2].trim().equals("1")) {
                int parent1 = findParent(map.get(relation[0]), parentRel);
                int parent2 = findParent(map.get(relation[1]), parentRel);
                System.out.println(parent1 == parent2);

            }
        }

    }

    public static void union(Integer u1, Integer u2, int[] parentRel) {
        int parent1 = findParent(u1, parentRel);
        int parent2 = findParent(u2, parentRel);
        parentRel[parent1] = parent2;
    }

    public static int findParent(Integer son, int[] parentRel) {
        if (parentRel[son] == son) {
            return parentRel[son];
        }
        parentRel[son] = findParent(parentRel[son], parentRel);
        return parentRel[son];
    }


}
